package com.his.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.his.commons.core.dto.PageInfo;
import com.his.commons.core.exception.HisException;
import com.his.commons.web.util.WebBeanUtils;
import com.his.controller.form.ModifyDepartmentForm;
import com.his.controller.form.NewDepartmentForm;
import com.his.controller.form.NewDisagnosisRoomForm;
import com.his.controller.form.PageForm;
import com.his.controller.info.DepartmentAndDisInfo;
import com.his.controller.info.DepartmentInfo;
import com.his.mapper.DisagnosisRoomMapper;
import com.his.model.Department;
import com.his.mapper.DepartmentMapper;
import com.his.model.DisagnosisRoom;
import com.his.service.DepartmentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.his.service.DisagnosisRoomService;
import com.his.util.DataAndTimeUtil;
import com.his.util.StringToTrimUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 梅津铧
 * @since 2022-03-22
 */
@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements DepartmentService {

    @Resource
    private DepartmentMapper departmentMapper;
    @Resource
    private DisagnosisRoomMapper disagnosisRoomMapper;
    @Resource
    private DisagnosisRoomService disagnosisRoomService;

    /**
     * 创建科室及下属诊室
     *
     * @param form 新科室信息
     */
    @Override
    public boolean increaseDepartment(NewDepartmentForm form) throws HisException {
        //判断字符串是否符合规定
        if(!StringToTrimUtil.StringToTrim(form.getDepartmentName()) | !StringToTrimUtil.StringToTrim(form.getDepartmentDescribe()) | !StringToTrimUtil.StringToTrim(form.getDepartmentState())){
            throw new HisException("请认真填写信息",500);
        }
        if(!form.getDepartmentName().contains("科")) throw new HisException("科室命名不合规",500);

        //新增科室（存入redis中）
        Department de = departmentMapper.selectOne(new QueryWrapper<Department>().eq("department_name", form.getDepartmentName()));
        if(de != null) throw new HisException("科室名已存在",500);
        Department department = new Department();
        department.setDepartmentName(form.getDepartmentName());
        department.setDepartmentDescribe(form.getDepartmentDescribe());
        department.setDepartmentCreatetime(DataAndTimeUtil.getTodayStartTime());
        department.setDepartmentState((form.getDepartmentState().equals("是")? 1:0));
        int insert = departmentMapper.insert(department);
        if(insert<=0) return false;

        //新增诊室（可使用消息队列）
        if(form.getDepartmentState().equals("是")){
            List<DisagnosisRoom> disagnosisRooms = new ArrayList<>();
            for (NewDisagnosisRoomForm dis : form.getDisagnosisRooms()) {
                DisagnosisRoom disagnosisRoom = new DisagnosisRoom();
                disagnosisRoom.setDisagnosisName(dis.getDisagnosisName());
                disagnosisRoom.setDisagnosisDescribe(dis.getDisagnosisDescribe());
                disagnosisRoom.setDepartmentId(department.getDepartmentId());
                disagnosisRooms.add(disagnosisRoom);
            }
            Integer i = disagnosisRoomMapper.increaseDis(disagnosisRooms);
            if(i<=0) throw new HisException("诊室添加失败",500);
        }
        return true;
    }

    /**
     * 更正科室及诊室信息
     *
     * @param form 更正的科室信息
     */
    @Override
    public boolean modifyDepartment(ModifyDepartmentForm form) throws HisException {
        //判断字符串是否符合规定
        if(!StringToTrimUtil.StringToTrim(form.getDepartmentName()) | !StringToTrimUtil.StringToTrim(form.getDepartmentDescribe()) | form.getDepartmentId()<=0
                | !StringToTrimUtil.StringToTrim(form.getDepartmentState()) | !StringToTrimUtil.StringToTrim(String.valueOf(form.getDepartmentId()))){
            throw new HisException("请认真填写信息",500);
        }
        if(!form.getDepartmentName().contains("科")) throw new HisException("科室命名不合规",500);

        //更正科室信息（存redis）
        Department department = new Department();
        department.setDepartmentName(form.getDepartmentName());
        department.setDepartmentDescribe(form.getDepartmentDescribe());
        department.setDepartmentState((form.getDepartmentState().equals("是")? 1:0));
        QueryWrapper<Department> departmentQueryWrapper = new QueryWrapper<>();
        departmentQueryWrapper.eq("department_id",form.getDepartmentId());
        int update = departmentMapper.update(department, departmentQueryWrapper);
        if(update<=0) throw new HisException("科室信息更新失败",500);

        //更新诊室信息（消息队列）
        //if(form.getDepartmentState().equals("是")){
            List<NewDisagnosisRoomForm> newdis = form.getDisagnosisRooms();
            List<DisagnosisRoom> nowdis = disagnosisRoomMapper.selectList(new QueryWrapper<DisagnosisRoom>().eq("department_id", form.getDepartmentId()));//已存在的诊室
            List<DisagnosisRoom> updatedis = new ArrayList<>();//需要更新的
            List<DisagnosisRoom> adddis = new ArrayList<>();//需要添加的
            List<DisagnosisRoom> deleteddis = new ArrayList<>();//需要删除的
            //得到更新的诊室信息
            for (NewDisagnosisRoomForm disagnosisRoom : newdis) {
                DisagnosisRoom disroom = new DisagnosisRoom();
                disroom.setDisagnosisName(disagnosisRoom.getDisagnosisName());
                disroom.setDisagnosisDescribe(disagnosisRoom.getDisagnosisDescribe());
                disroom.setDepartmentId(department.getDepartmentId());

                for (int i = 0; i < nowdis.size(); i++) {
                    if(disagnosisRoom.getDisagnosisName().equals(nowdis.get(i).getDisagnosisName())){
                        disroom.setDepartmentId(nowdis.get(i).getDepartmentId());
                        disroom.setDisagnosisId(nowdis.get(i).getDisagnosisId());
                        updatedis.add(disroom);
                        nowdis.remove(i);
                        newdis.remove(disagnosisRoom);
                    }
                }
            }
            if(updatedis.size()>0){
                boolean b = disagnosisRoomService.updateBatchById(updatedis, updatedis.size());//更新
                if(!b) throw new HisException("诊室信息更正失败",500);
            }

            if(newdis.size()>0 && form.getDepartmentState().equals("是")){ //添加
                adddis = WebBeanUtils.copyList(newdis, DisagnosisRoom.class);//待添加的
                for (DisagnosisRoom adddi : adddis) {
                    adddi.setDepartmentId(department.getDepartmentId());
                }
                Integer integer = disagnosisRoomMapper.increaseDis(adddis);
                if(integer<=0) throw new HisException("诊室信息更正失败",500);
            }

            if(nowdis.size()>0){ //删除
                List<Integer> integers = new ArrayList<>();
                for (DisagnosisRoom nowdi : nowdis) {
                    integers.add(nowdi.getDisagnosisId());
                }
                QueryWrapper<DisagnosisRoom> wrapper = new QueryWrapper<>();
                wrapper.in("disagnosis_id",integers);
                int delete = disagnosisRoomMapper.delete(wrapper);
                if(delete<=0) throw new HisException("诊室信息更新失败",500);
            }
        //}
        return true;
    }

    /**
     * 获取所有科室信息
     *
     * @param pageForm 分页信息
     * @return  科室信息
     */
    @Override
    public PageInfo<DepartmentInfo> obtainDepartments(PageForm pageForm) throws HisException {
        //判断分页信息
        if(null== pageForm.getPagesize() | null==pageForm.getPagenum()) throw new HisException("请认真填写信息",500);
        if(!StringToTrimUtil.StringToTrim(String.valueOf(pageForm.getPagenum())) | !StringToTrimUtil.StringToTrim(String.valueOf(pageForm.getPagesize()))){
            throw new HisException("请认真填写信息",500);
        }
        if(pageForm.getPagenum()<1 | pageForm.getPagesize()<1) throw new HisException("请认真填写信息",500);
        //获取科室信息
        Page<Department> departmentPage = new Page<>();
        departmentPage.setSize(pageForm.getPagesize());departmentPage.setCurrent(pageForm.getPagenum());

        Page<Department> departmentPages = departmentMapper.selectPage(departmentPage, null);
        if(null == departmentPages.getRecords()) throw new HisException("查询失败",500);
        List<DepartmentInfo> departmentInfos = WebBeanUtils.copyList(departmentPage.getRecords(), DepartmentInfo.class);
        for (int i = 0; i < departmentInfos.size(); i++) {
            if(departmentPage.getRecords().get(i).getDepartmentState()==0){
                departmentInfos.get(i).setDepartmentState("否");
            }else{
                departmentInfos.get(i).setDepartmentState("是");
            }
        }

        PageInfo<DepartmentInfo> departmentInfoPageInfo = new PageInfo<>();
        departmentInfoPageInfo.setPageNum(departmentPage.getCurrent());
        departmentInfoPageInfo.setPageSize(departmentPage.getSize());
        departmentInfoPageInfo.setTotalPage(departmentPage.getTotal());
        departmentInfoPageInfo.setRecord(departmentInfos);

        return departmentInfoPageInfo;
    }

    /**
     * 根据科室编号/名称获取科室信息
     *
     * @param condition 科室编号/名称
     * @return  科室信息
     */
    @Override
    public DepartmentInfo obtainByCondition(String condition) throws HisException {
        //去除空格和空字符后，检验查询信息
        if(!StringToTrimUtil.StringToTrim(condition)){
            throw new HisException("请认真填写信息",500);
        }
        //根据查询条件查询
        QueryWrapper<Department> wrapper = new QueryWrapper<>();
        wrapper.like("department_id",condition).or().like("department_name",condition);
        Department department = departmentMapper.selectOne(wrapper);
        if(null == department) throw new HisException("该科室不存在",500);
        DepartmentInfo departmentInfo = WebBeanUtils.copyObject(department, DepartmentInfo.class);
        if(department.getDepartmentState()==1){
            departmentInfo.setDepartmentState("是");
        }else {
            departmentInfo.setDepartmentState("否");
        }
        return departmentInfo;
    }

    /**
     * 获取有诊室的科室信息
     *
     * @return  诊室信息
     */
    @Override
    public List<DepartmentAndDisInfo> ObtainHasDis() throws HisException {
        QueryWrapper<Department> wrapper = new QueryWrapper<>();
        wrapper.eq("department_state",1);

        List<Department> departments = departmentMapper.selectList(wrapper);
        if(null == departments) throw new HisException("获取目标诊室失败",500);
        List<DepartmentAndDisInfo> departmentInfos = WebBeanUtils.copyList(departments, DepartmentAndDisInfo.class);

        return departmentInfos;
    }

    /**
     * 解散科室及下属诊室
     *
     * @param departmentId 科室id
     */
    @Override
    public boolean logoutById(Integer departmentId) throws HisException {
        //去除空格和空字符后，检验查询信息
        if(!StringToTrimUtil.StringToTrim(String.valueOf(departmentId))){
            throw new HisException("请认真填写信息",500);
        }

        //删除科室
        QueryWrapper<Department> wrapper = new QueryWrapper<>();
        wrapper.eq("department_id",departmentId);
        Department department = departmentMapper.selectOne(wrapper);
        if(null == department) throw new HisException("该科室不存在",500);
        int delete = departmentMapper.delete(wrapper);
        if(delete<=0) throw new HisException("解散科室失败，请稍后重试",500);

        //删除下属诊室
        if(1 == department.getDepartmentState()){
            QueryWrapper<DisagnosisRoom> disagnosisRoomQueryWrapper = new QueryWrapper<>();
            disagnosisRoomQueryWrapper.eq("department_id",departmentId);
            int deletedis = disagnosisRoomMapper.delete(disagnosisRoomQueryWrapper);
        }
        return true;
    }

    /**
     * 获取无诊室的科室信息
     *
     * @return 科室信息
     */
    @Override
    public List<DepartmentAndDisInfo> ObtainHasNotDis() throws HisException {

        QueryWrapper<Department> wrapper = new QueryWrapper<>();
        wrapper.eq("department_state",0);

        List<Department> departments = departmentMapper.selectList(wrapper);
        if(null == departments) throw new HisException("获取目标诊室失败",500);
        List<DepartmentAndDisInfo> departmentInfos = WebBeanUtils.copyList(departments, DepartmentAndDisInfo.class);

        return departmentInfos;
    }
}
